
<template>
  <div
    class="container"
    v-show="!showChange"
  >
    <div style="float: left; min-width:450px !important;">
      <div class="companyTree">
        <div class="title">
          <div>事件类型</div>
          <div>
            <el-button
              type="primary"
              @click="templateDownload()"
            >模版下载</el-button>
            <el-button
              type="primary"
              @click="importEvent()"
            >导入</el-button>
            <el-button
              type="primary"
              @click="addTopEvent()"
            >新增</el-button>
          </div>
        </div>
        <div class="tree">
          <el-input
            class="search"
            v-model="filterText"
            placeholder
            :suffix-icon="Search"
          />
          <div style="height: 700px; overflow-y: scroll; overflow-x: hidden">
            <el-tree
              ref="treeRef"
              class="filter-tree"
              :data="companyData"
              :props="defaultProps"
              default-expand-all
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span class="custom-tree-node-left">
                    <span class="custom-tree-node-left-label">
                      <el-tooltip
                        class="box-item"
                        effect="dark"
                        :content="node.label"
                        placement="top"
                        >
                        {{ node.label }}
                      </el-tooltip>

                    </span>
                  </span>
                  <span class="oper">
                    <el-icon
                      class="el-input__icon"
                      color="#427CC9"
                      @click="addEvent(data, node)"
                    >
                      <CirclePlus />
                    </el-icon>
                    <el-icon
                      class="el-input__icon"
                      color="#427CC9"
                      @click="editEvent(data, node)"
                    >
                      <EditPen />
                    </el-icon>
                    <el-popconfirm
                      title="是否删除?"
                      confirmButtonText="确定"
                      cancelButtonText="取消"
                      @confirm="() => deleteTypeFn(data, node)"
                    >
                      <template #reference>
                        <el-icon
                          class="el-input__icon"
                          color="#e13e53"
                        >
                          <Delete />
                        </el-icon>
                      </template>
                    </el-popconfirm>

                  </span>
                </span>
              </template>
            </el-tree>
          </div>
        </div>
      </div>
    </div>
    <div style="float: left; width: 72%; height: auto">
      <layout-card
        v-model="search"
        :filters="isExampleOptions"
        headline="数据列表"
        headtitle="数据筛选"
        :hasButton="true"
        @search-change="getData"
        @search-reset="resetGetData"
      >
        <template #action>
          <el-button
            type="primary"
            @click="handleCreate"
          >新增</el-button>
        </template>

        <table-common
          :loading="loading"
          :columns="exampleColumns"
          :pagination="pager"
          :table-data="tabeData"
          size="small"
          @sort-change="sortChange"
          @current-change="myChangeCurrent"
          @size-change="myChangePageSize"
          stripe
        >
          <template #action="{ row }">
            <!-- 自定义操作栏示例  -->
            <el-button
              class="link-btn"
              @click="handleEdit(row)"
              link
              type="primary"
            >编辑</el-button>
            <el-popconfirm
              :title="row.enabled ==1 ? '是否挂起?':'是否启用?'"
              confirmButtonText="确定"
              cancelButtonText="取消"
              @confirm="() => suspended(row)"
            >
              <template #reference>
                <el-button
                  class="link-btn"
                  link
                  type="danger"
                >{{row.enabled ==1 ? '挂起':'启用'}}</el-button>
              </template>
            </el-popconfirm>
          </template>
        </table-common>
      </layout-card>
    </div>
  </div>
  <div v-show="showChange">
    <ChangeMessae
      :key="timer"
      @onCancel="onCancel"
      @onConfirm="onConfirm"
      ref="changeRef"
    ></ChangeMessae>
  </div>
  <edit-dialog
    :centerDialogVisible="centerDialogVisible"
    :tilte="dialogTilte"
    :key="timer"
    :width="500"
    align-center
    :defaultButton="false"
  >
    <template #content>
      <template v-if="dialogTilte === '模板下载'">
        <table-common
          :columns="modelColumns"
          :table-data="dialogType2"
          :height="300"
          size="small"
          :pagination="false"
          :row-key="getRowKey"
          lazy
          :load="load"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          stripe
        >
          <template #action="{ row }">
            <!-- 自定义操作栏示例  -->
            <el-button
              class="link-btn"
              @click="preview(row)"
              link
              type="primary"
            >预览</el-button>
            <el-button
              class="link-btn"
              @click="download(row)"
              link
              type="primary"
            >下载</el-button>
          </template>
        </table-common>
      </template>
      <template v-if="dialogTilte === '导入'">
        <p style="margin-bottom: 10px; margin-left: 20px;">
          {{ pTitle }}:&nbsp;&nbsp;{{ pTitle2 }}
        </p>
        <div class="mb-2 flex items-center text-sm">
          <el-radio-group
            v-model="radioValue"
            class="elRadio"
          >
            <el-radio
              v-for="(item, index) in dialogType2"
              :key="item.id"
              :label="item.id"
              size="large"
            >
              {{
                  item.label
              }}
            </el-radio>
          </el-radio-group>
        </div>
      </template>
      <template v-if="dialogTilte === '新增事件类型'">
        <p
          style="margin-bottom: 10px; margin-left: 20px;"
          v-if="pTitle"
        >
          {{ pTitle }}:&nbsp;&nbsp;{{ pTitle2 }}
        </p>
        <FilterBar
          :rules="typeRules"
          :filters="dialogType2"
          ref="rootTreeType"
        ></FilterBar>

      </template>
      <template v-if="dialogTilte === '编辑事件类型'">
        <FilterBar
          :rules="typeRules"
          :filters="dialogType2"
          ref="rootTreeType"
        ></FilterBar>
      </template>
    </template>
    <template #custom>
      <span
        class="dialog-footer"
        v-if="dialogTilte === '模板下载'"
      >

        <el-button @click="Cancel">关闭</el-button>
      </span>
      <span
        class="daoru"
        v-if="dialogTilte === '导入'"
      >
        <el-button
          @click="Cancel"
          style="margin-right: 5px;"
        >取消</el-button>
        <!-- <el-button type="primary" @click="Submit">选择文件</el-button> -->
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          class="upload-demo"
          style="margin-left: 5px;"
          action="#"
          accept=".xlsx"
          :file-list="fileList"
          :show-file-list="false"
          :http-request="handleUpload"
          :on-success="handleuploadSuccess"
          :on-change="handleChange"
        >
          <el-button
            type="primary"
            @click="onloadSubmit"
          >选择文件</el-button>
        </el-upload>
      </span>
      <span
        class="dialog-footer"
        v-if="dialogTilte === '新增事件类型' || dialogTilte === '编辑事件类型'"
      >
        <el-button @click="Cancel">取消</el-button>
        <el-button
          type="primary"
          @click="Submit"
          :loading="loadingButton"
        >保存</el-button>
      </span>
    </template>
  </edit-dialog>
  <!-- 文件预览弹窗 -->
  <edit-dialog
    :centerDialogVisible="centerDialogPreviewVisible"
    tilte="文件预览"
    :key="timer"
    :width="1000"
    align-center
    :defaultButton="false"
    @cancel="previewCancel"
  >
    <template #content>
      <!-- <vue-office-docx
        :src="doc"
        style=" width: 100%;height:400px;"
        @rendered="renderedHandler"
        @error="errorHandler"
      /> -->
      <vue-office-excel
        :src="doc"
        style=" width: 100%;height:400px;"
        @rendered="renderedHandler"
        @error="errorHandler"
      />
    </template>
  </edit-dialog>
</template>
<script setup lang="ts">
// 需要导入watch监听
import { computed, ref, onBeforeMount, nextTick, watch, reactive, onMounted } from 'vue'
// 以下两项需要导入
import { ElTree, ElMessage } from 'element-plus'
import { Download, Search } from '@element-plus/icons-vue'
// 7-18修改LayoutCard 页面，hasButton参数为false时显示为弹窗样式，为true时显示为搜索栏样式
import LayoutCard from '@/components/LayoutCard/index.vue'
import TableCommon from '@/components/TableCommon/index.vue'
import { exampleColumns, modelColumns } from './config/columns'
import { usePagination } from 'vue-request'
import editDialog from '@/components/editDialog/index.vue'
import { useStore } from 'vuex'
import type { FormInstance } from 'element-plus'
import { exampleOptions, dialogAddOptions } from './config/filters'
import FilterBar from '@/components/FilterBar/index.vue'
import ChangeMessae from './components/ChangeMessae/index.vue'
import {
  eventRulesFindTree,
  eventRulesAppendType,
  eventRulesEditType,
  eventRulesDeleteType,
  eventInfoFindPage,
  eventInfoAppend,
  eventInfoUpdate,
  eventInfoUpdateStatus,
  eventRulesImport,
  eventRulesTemplateDownload
} from '@/api/eventManage/eventRules'
import { getResource } from "@/api/resource";
import { typeRules } from './config/rules'
import { dayjs } from 'element-plus'
// import VueOfficeDocx from '@vue-office/docx'
// import '@vue-office/docx/lib/index.css'
import VueOfficeExcel from '@vue-office/excel'
import '@vue-office/excel/lib/index.css'
const Service = (data: ListParams) => {

}

// =============模拟接口数据==END
const {
  run,
  data,
  loading,
  current,
  pageSize,
  total,
  changeCurrent,
  changePageSize
} = usePagination(Service, {
  manual: true,
  pagination: {
    currentKey: 'pageNum',
    pageSizeKey: 'pageSize',
    totalKey: 'data.total'
  }
})

const search = ref<FilterDataType>({})
const myTotal = ref(0)
const pager = computed(() => ({
  currentPage: current.value,
  pageSize: pageSize.value,
  total: myTotal.value,
  // 7-24 手动设置了总页数
  pageCount: myTotal.value === 0 ? 1 : Math.ceil(myTotal.value / pageSize.value)
}))
//查询表单
const isExampleOptions = ref(exampleOptions)
// 单选按钮
const radioValue = ref('')
// 新增弹窗是否打开
const centerDialogVisible = ref(false)
// 文件预览弹窗
const centerDialogPreviewVisible = ref(false)
// 弹窗标题
const dialogTilte = ref('')
// 弹窗页面类型
const dialogType = ref()
// 页面弹窗类型二
const dialogType2 = ref()
// 弹窗二级标题一
const pTitle = ref()
// 弹窗二级标题二
const pTitle2 = ref()
// 时间戳，用于确保弹窗页面能加载不同的界面
const timer = ref()
// 用于弹窗提交按钮,默认为false
const loadingButton = ref(false)
//新增根节点
const rootTreeType = ref<FormInstance>()
//模糊搜索事件类型
const filterText = ref('')
const treeRef = ref('')
// 请求用户的权限树
const { getters } = useStore()
// 拿到vuex里面用户的信息
// const organTree = computed(() => getters['user/getOrganTree'])

const Users = computed(() => getters['user/getUserInfo'])
//表格数据
const tabeData = ref([])
//当前选中树节点
const eventType = ref({ id: '', typeName: '', parentName: '' })
//是否打开修改信息页面
const showChange = ref(false)
//changeMesage 实例
const changeRef = ref()
//事件等级-字典
const eventLevel = ref()
//区域处置单位-字典
const processGroup = ref()
//执行的操作是否是树的操作
const isControlsTree = ref(false)
//上传
const uploadRef = ref()
//上传文件列表
const fileList = ref()
//排序规则
const isOrder = ref([])
const doc = ref()
//关闭changeMesage
const onCancel = () => {
  showChange.value = false
  //  changeRef.value.setInfoValue({
  //   exigenceLevel: '',
  //   result: '',
  //   eventLevel: '',
  //   eventTypeNum: '',
  //   processGroup: '',
  //   enable: ''
  // })
  // changeRef.value.setForewarningValue({
  // })
  // changeRef.value.setIntoAccident({
  // })
  // changeRef.value.setEvaluate({
  // })
}
const previewCancel = () => {
  centerDialogPreviewVisible.value = false
}
/**
 * 预览
 */
const preview = async () => {
  eventRulesTemplateDownload({}).then((res) => {
    const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
    doc.value = URL.createObjectURL(blob)
    centerDialogPreviewVisible.value = true
  })
}
/**
 * 模板文件下载
 */
const download = () => {
  eventRulesTemplateDownload({}).then((res) => {
    const link = document.createElement('a')
    const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
    link.style.display = 'none'
    link.href = URL.createObjectURL(blob)
    link.setAttribute(
      'download',
      // `事件规则管理${dayjs().format('YYYYMMDD')}.xlsx`
      `事件规则管理.xlsx`
    )
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  })
    .catch((err: any) => {
      ElMessage.error(err?.message || '导出失败')
    })
}
watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
//导入
const handleChange = (uploadFile) => {
  if(!radioValue.value) return ElMessage.error('请选择父级事件类型')
  const uploadPayLoad = {
    file: uploadFile.raw,
    id: radioValue.value
  }
  const response = eventRulesImport(uploadPayLoad)
  response.then(res => {
    if (res.code === '1') {
      ElMessage.success('导入成功')
      getTreeData()
      centerDialogVisible.value = false
      radioValue.value = ''
    } else {
      ElMessage.error('导入失败')
    }
  })
}
// 树形结构搜索过滤
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.label.includes(value)
}
/**
 * 点击树形节点
 */
const handleNodeClick = (data, node, treeNode, e) => {
  if (isControlsTree.value) return isControlsTree.value = false
  if (node.childNodes.length) return
  eventType.value.id = data.id
  eventType.value.typeName = data.label
  eventType.value.parentName = node.parent.data.label
  getData()
}
// 打开新增窗口
const handleCreate = async () => {
  // timer.value = new Date().getTime()
  const { id, typeName, parentName } = eventType.value
  if (!id) return ElMessage.error('请选择事件类型')
  showChange.value = true
  await changeRef.value.setInfoValue({
    parentTpye: parentName,
    eventTypeName: typeName,
    id,
    title: '新增',
    // exigenceLevel: '',
    // result: '',
    // eventLevel: '',
    // eventTypeNum: '',
    // processGroup: '',
    // enable: ''
  })
  // changeRef.value.setForewarningValue({
  //   isForewarning: '',
  //   personThreshold: '',
  //   forewarningContent: ''
  // })
  // changeRef.value.setIntoAccident({
  //   isenable: '',
  //   intoPersonThreshold: '',
  //   eventLevelThreshold: '',
  //   exigenceLevelThreshold: '',
  //   intoForewarningContent: ''
  // })
  // changeRef.value.setEvaluate({
  //   evaluateIsenable: '',
  //   responseTime: '',
  //   responseWeight: '',
  //   responseSectionStart: '',
  //   responseSectionEnd: '',

  //   processing: '',
  //   processingWeight: '',
  //   processingSectionStart: '',
  //   processingSectionEnd: '',

  //   ultimate: '',
  //   ultimateWeight: '',
  //   ultimateSectionStart: '',
  //   ultimateSectionEnd: '',
  // })
}
/**
 * 打开编辑窗口
 */
const handleEdit = (row) => {
  // timer.value = new Date().getTime()
  const { id, typeName, parentName } = eventType.value
  if (!id) return ElMessage.error('请选择事件类型')

  const { emergencyLevel, result, eventLevel, eventTypeNum, processGroup, enabled,
    enableAlert, alertPersonValue, alertContent, enableIncident, incidentPersonValue,
    incidentEventLevel, incidentEmergencyLevel, incidentContent, enableReview,
    responseTime, processMethod, finalImpact } = row
  let processGroupIds = []
  for(let item of row.processGroup){
    processGroupIds.push(item.id)
  }
  showChange.value = true
  changeRef.value.setInfoValue({
    parentTpye: parentName,
    eventTypeName: typeName,
    id,
    title: '编辑',
    typeMessageId: row.id,
    exigenceLevel: emergencyLevel,
    result,
    eventLevel: eventLevel?.value,
    eventTypeNum,
    processGroup: processGroupIds,
    enable: enabled + ''
  })
  changeRef.value.setForewarningValue({
    isForewarning: enableAlert + '',
    personThreshold: alertPersonValue,
    forewarningContent: alertContent
  })
  changeRef.value.setIntoAccident({
    isenable: enableIncident + '',
    intoPersonThreshold: incidentPersonValue,
    eventLevelThreshold: incidentEventLevel,
    exigenceLevelThreshold: incidentEmergencyLevel,
    intoForewarningContent: incidentContent
  })
  changeRef.value.setEvaluate({
    evaluateIsenable: enableReview + '',
    responseTime: responseTime[0].time,
    responseWeight: responseTime[0].weight,
    responseSectionStart: responseTime[0].scoreStart,
    responseSectionEnd: responseTime[0].scoreEnd,

    processing: processMethod[0].processMethod,
    processingWeight: processMethod[0].weight,
    processingSectionStart: processMethod[0].scoreStart,
    processingSectionEnd: processMethod[0].scoreEnd,

    ultimate: finalImpact[0].finalImpact,
    ultimateWeight: finalImpact[0].weight,
    ultimateSectionStart: finalImpact[0].scoreStart,
    ultimateSectionEnd: finalImpact[0].scoreEnd,
  })
}
// 去掉空格
const removeSpace = (val: string) => {
  if (val) {
    if (val.includes(' ')) {
      val = val.replace(/\s/g, '')
    }
  }

  return val
}
/**
 * 新增/编辑保存
 */
const onConfirm = async (data) => {
  //事件基本信息
  const { id: typeId, parentTpye, eventTypeName, exigenceLevel, result, eventLevel, eventTypeNum, processGroup, enable, title } = data.eventInfo
  //事件预警规则
  const { isForewarning, personThreshold, forewarningContent } = data.eventForewarning
  //事件转事故
  const { isenable, intoPersonThreshold, eventLevelThreshold, exigenceLevelThreshold, intoForewarningContent } = data.eventIntoAccident
  //事件评价规则
  const {
    evaluateIsenable,
    responseTime,
    responseWeight,
    responseSectionStart,
    responseSectionEnd,
    processing,
    processingWeight,
    processingSectionStart,
    processingSectionEnd,
    ultimate,
    ultimateWeight,
    ultimateSectionStart,
    ultimateSectionEnd } = data.eventEvaluate
  const { userId: id, name, organId, organName } = Users.value

  const payload = {
    creator: { id, name, organId, organName },
    owner: { id, name, type: 'PERSONAL' },
    //事件基本信息
    //事件类型id
    eventTypeId: typeId,
    //事件类型来源
    eventTypeSource: eventTypeName,
    //紧急程度
    emergencyLevel: exigenceLevel,
    //后果
    result: removeSpace(result),
    //事件等级
    eventLevel,
    //事件等级编号
    eventTypeNum: removeSpace(eventTypeNum),
    //区域处置单位
    processGroup: [{ id: processGroup, name: processGroup }],
    //状态
    enabled: enable,
    //事件预警规则
    //是否预警
    enableAlert: isForewarning,
    //事件预警_人数影响阈值
    alertPersonValue: personThreshold,
    //事件预警_内容
    alertContent: removeSpace(forewarningContent),
    //事件转事故
    //是否转事故
    enableIncident: isenable,
    //转事故_人数影响阈值
    incidentPersonValue: intoPersonThreshold,
    //转事故_事件等级
    incidentEventLevel: eventLevelThreshold,
    //转事故_事件紧急程度
    incidentEmergencyLevel: exigenceLevelThreshold,
    //转事故_预警内容
    incidentContent: removeSpace(intoForewarningContent),
    //事件评价规则
    //是否事件评价
    enableReview: evaluateIsenable,
    //响应事件
    responseTime: [{
      time: removeSpace(responseTime),
      weight: removeSpace(responseWeight),
      scoreStart: responseSectionEnd ? responseSectionStart ?  responseSectionStart: 0 : '',
      scoreEnd: responseSectionEnd
    }],
    //处理方式
    processMethod: [{
      processMethod: removeSpace(processing),
      weight: removeSpace(processingWeight),
      scoreStart: processingSectionEnd ? processingSectionStart ?  processingSectionStart: 0 : '',
      scoreEnd: processingSectionEnd
    }],
    //最终影响
    finalImpact: [{
      finalImpact: removeSpace(ultimate),
      weight: removeSpace(ultimateWeight),
      scoreStart: ultimateSectionEnd ? ultimateSectionStart ?  ultimateSectionStart: 0 : '',
      scoreEnd: ultimateSectionEnd
    }]
  }
  // 触发验证
  const flagInfoRuleFormRef = await changeRef.value?.InfoRuleFormRef();
  const flagForewarningRuleFormRef = await changeRef.value?.ForewarningRuleFormRef();
  const flagIntoAccidentRuleFormRef = await changeRef.value?.IntoAccidentRuleFormRef();
  const flagEvaluateRuleFormRef = await changeRef.value?.EvaluateRuleFormRef();
  if (!(flagInfoRuleFormRef === true && flagForewarningRuleFormRef === true && flagIntoAccidentRuleFormRef === true && flagEvaluateRuleFormRef === true)) {
    return
  }
  if (title === '新增') {
    eventInfoAppend(payload).then(response => {
      if (response.code === '1') {
        ElMessage.success('新增成功')

      } else {
        ElMessage.err('新增失败')
      }
      getData()
    })
  } else if (title === '编辑') {

    payload.id = data.eventInfo.typeMessageId
    eventInfoUpdate(payload).then(response => {
      if (response.code === '1') {
        ElMessage.success('编辑成功')
      } else {
        ElMessage.err('编辑失败')
      }
      getData()
    })
  }

  showChange.value = false
  changeRef.value?.resetEnabled()
  changeRef.value?.onReset()
}
/**
 * 挂起
 */
const suspended = async (row) => {
  let enabled
  if (row.enabled == 0) {
    // ElMessage.warning('该行数据已挂起')
    // return
    enabled = 1
  }else{
    enabled = 0
  }
  const state = await eventInfoUpdateStatus({
    id: row.id,
    enabled
  })
  if (state.code === '1') {
    ElMessage.success('操作成功')
    getData()
  } else {
    ElMessage.error('操作失败')
  }
}

// 模板下载(左侧树)
const templateDownload = () => {
  timer.value = new Date().getTime()
  dialogType2.value = companyData.value.map(item => ({ id: item.id, typeName: item.label, value: item.value }))
  dialogTilte.value = '模板下载'
  centerDialogVisible.value = true
}

// 导入(左侧树)
const importEvent = () => {
  timer.value = new Date().getTime()
  dialogType2.value = companyData.value.map(item => ({ id: item.id, label: item.label, value: item.value }))
  dialogTilte.value = '导入'
  pTitle.value = '请选择本次导入的事件类型'
  pTitle2.value = ''
  centerDialogVisible.value = true
}
/**
 *  新增顶层节点
 */
const addTopEvent = () => {

  timer.value = new Date().getTime()
  dialogType2.value = dialogAddOptions
  dialogTilte.value = '新增事件类型'
  nextTick(() => {
    rootTreeType.value.setFieldsValue({
      tier: '0'
    })
  })
  pTitle.value = ''
  pTitle2.value = ''
  centerDialogVisible.value = true
}
/**
 * 判断是否有事件类型基本信息
 */
const haveMessageTOrF = async (id) => {
  const payload = {
    condition: {
      eventTypeId: id
    },
    pageNum: current.value,
    pageSize: pageSize.value,
  }
  const haveMessage = await eventInfoFindPage(payload)
  if (haveMessage.data.total) return 0
  else return 1
}
// 新增(左侧树)
const addEvent = async (row, node) => {
  isControlsTree.value = true
  if(row.tier === '6') return  ElMessage.error('该节点不可操作:超出最大层级')
  // if(node.childNodes.length) return  ElMessage.error('该节点不可操作:已有子类型')
  if (!await haveMessageTOrF(row.id)) return ElMessage.error('该节点不可操作:已有事件类型基本信息')
  const { id, tier, label } = row
  timer.value = new Date().getTime()
  dialogType2.value = dialogAddOptions
  dialogTilte.value = '新增事件类型'
  nextTick(() => {
    rootTreeType.value.setFieldsValue({
      pid: id,
      tier: tier
    })
  })
  pTitle.value = '父级分类'
  pTitle2.value = label
  centerDialogVisible.value = true
}
/**
 * 编辑左侧树
 */
const editEvent = async (row, node) => {
  isControlsTree.value = true
  // if (node.childNodes.length) return ElMessage.error('该节点不可操作:已有子类型')
  if (!await haveMessageTOrF(row.id)) return ElMessage.error('该节点不可操作:已有事件类型基本信息')
  const { parent: { data: { id: pid } } } = node
  const { id, label } = row
  timer.value = new Date().getTime()
  dialogType2.value = dialogAddOptions
  dialogTilte.value = '编辑事件类型'
  nextTick(() => {
    rootTreeType.value.setFieldsValue({
      typeId: id,
      typename: label,
      pid
    })
  })
  pTitle.value = ''
  pTitle2.value = ''
  centerDialogVisible.value = true
}

const companyData = ref([
])


/**
 * 弹窗点击确认
 */
const Submit = async () => {
  //去除空格
  const { typename } = rootTreeType.value.getParams()
  const newtypename = typename ? typename.replace(/\s+/g, '') : typename
  await nextTick(() => {
    rootTreeType.value.setFieldsValue({
      typename: newtypename
    })
  })
  const flag = await rootTreeType.value?.validateRuleFormRef()
  if (!flag) return
  loadingButton.value = true
  let isClose = false
  if (dialogTilte.value === '新增事件类型') {
    isClose = await appendTypeFn()
  } else if (dialogTilte.value === '编辑事件类型') {
    isClose = await editTypeFn()
  }
  loadingButton.value = false
  if (isClose) {
    centerDialogVisible.value = false
  }
  getTreeData()
}

/**
 * 删除事件类型
 */
const deleteTypeFn = async (row, node) => {

  isControlsTree.value = true
  if (node.childNodes.length) return ElMessage.error('该节点不可操作:已有子类型')
  if (!await haveMessageTOrF(row.id)) return ElMessage.error('该节点不可操作:已有事件类型基本信息')
  const { parent: { data: { id: pid } } } = node
  const { id: typeId, label: typename } = row
  const { userId: id, name, organId, organName } = Users.value
  const params = {
    id: typeId,
    mender: { id, name, organId, organName },
    name: typename,
    pid
  }
  const editType = await eventRulesDeleteType(params)

  if (editType.code === '1') {
    ElMessage.success('删除成功')
  } else {
    ElMessage.error('删除失败')
  }
  getTreeData()
}
/**
 * 编辑事件类型
 */
const editTypeFn = async () => {
  const { typeId, typename, pid } = rootTreeType.value.getParams()
  const { userId: id, name, organId, organName } = Users.value

  const params = {
    id: typeId,
    mender: { id, name, organId, organName },
    name: typename,
    pid
  }
  const editType = await eventRulesEditType(params)
  if (editType.code === '1') {
    ElMessage.success('编辑成功')
    return 1
  } else {
    ElMessage.error('编辑失败')
    return 0
  }
}
/**
 * 新增事件类型
 */
const appendTypeFn = async () => {
  const { pid, typename, tier } = rootTreeType.value.getParams()
  const { userId: id, name, organId, organName } = Users.value

  const params = {
    creator: { id, name, organId, organName },
    name: typename,
    owner: { id, name, type: 'PERSONAL' },
    parentTier: tier,
    pid

  }
  const appendType = await eventRulesAppendType(params)
  if (appendType.code === '1') {
    ElMessage.success('新增成功')
    return 1
  } else if (appendType.code === '0') {
    ElMessage.error('新增失败:该类型已存在')
  } else {
    ElMessage.error('新增失败')
  }
  return 0
}
//获取分页查询入参
const getParams = () => {

  const payload = {
    condition: {
      eventTypeId: eventType.value.id
    },
    pageNum: current.value,
    pageSize: pageSize.value,
  }
  const { status, region, consequence, level } = search.value
  const result = consequence?.replace(/\s+/g, '')
  if (result) {
    payload.condition.result = result
  }
  if (status) {
    payload.condition.enabled = status
  }
  if (region) {
    payload.condition.processGroupName = region
  }

  if (level?.length) {
    payload.condition.eventLevel = level
  }
  if (isOrder.value.length) {
    payload.condition.order = isOrder.value
  }else{
    payload.condition.order = [{ column: 'enabled', method: 'DESC' },{ column: 'event_level', method: 'ASC' },{column: 'create_time', method: 'DESC'}]
  }
  return payload

}
// 获取数据
const getData = async () => {

  loading.value = true
  const payload = getParams()
  if(!payload.condition.eventTypeId){
    loading.value = false
    return
  }
  //获取表格数据
  const getTableData = await eventInfoFindPage(payload).finally(() => {
    loading.value = false
  })

  getTableData.data.list.forEach(item => {
    eventLevel.value.forEach(level => {
      if (level.value === item.eventLevel) {
        item.eventLevel = { name: level.label, value: level.value }
      }
    })
    let processList = []
    processGroup.value.forEach(process => {

      item.processGroup.forEach(itemObj => {
        try {
          itemObj.name.forEach(nameObj => {
            if(nameObj === process.value){
              processList.push({ name: process.label, id: process.value })
            }
          })
        } catch (error) {
          if (process.value === item.processGroup[0].name) {
            processList.push({ name: process.label, id: process.value })
          }
        }
      })

      // if (process.value === item.processGroup[0].name) {
      //   item.processGroup = [{ name: process.label, id: process.value }]
      // }
    })
    item.processGroup = processList
  })
  tabeData.value = getTableData.data.list
  changeCurrent(getTableData.data.pageNum)
  changePageSize(getTableData.data.pageSize)
  myTotal.value = getTableData.data.total
  const isparams = {
    pageNum: current.value,
    pageSize: pageSize.value
  }
  run(isparams)
  // getTableData.finally(() => loading.value = false)
  // run(params)
}
/**
 * 获取树形结构数据
 */
const getTreeData = () => {
  //左侧树形结构
  const getTree = eventRulesFindTree({})
  getTree.then(res => companyData.value = res.data.map(item => handleTreeData(item)))
}
/**
 * 递归处理树的结构
 */
const handleTreeData = (treeData) => {
  return {
    id: treeData.id,
    label: treeData.name,
    value: treeData.id,
    tier: treeData.tier,
    children: treeData.children.map(child => handleTreeData(child))
  }
}
// 点击取消按钮
const Cancel = () => {
  pTitle.value = ''
  pTitle2.value = ''
  dialogTilte.value = ''
  dialogType.value = ''
  dialogType2.value = ''
  centerDialogVisible.value = false
  radioValue.value = ''
}
/**
 * 功能-点击排序
 * @param value 排序规则
 */
const sortChange = (value) => {
  let sort = value.order?.slice(0, -6) || 'DESC'
  sort = sort.toUpperCase()
  let order = []
  if (value.prop === 'eventTypeNum') {
    order = [{ column: 'event_type_num', method: sort }]
  } else if (value.prop === 'eventLevel') {
    order = [{ column: 'event_level', method: sort }]
  } else if (value.prop === 'createTime') {
    order = [{ column: 'create_time', method: sort }]
  } else if (value.prop === 'enabled') {
    order = [{ column: 'enabled', method: sort }]
  }
  isOrder.value = order

  getData()
}
/**
 * 获取数据字典内容
 */
const getEventResource = async () => {
  //事件规则管理-事件等级
  const responseLevel = await getResource('event_rules_event_level')
  isExampleOptions.value[0].inputProps.options = responseLevel.data.properties.meta
  isExampleOptions.value[0].inputProps.options.unshift({ label: "全部", value: "" })
  eventLevel.value = responseLevel.data.properties.meta
  //事件规则管理-区域处置单位
  const responseProcess = await getResource('event_rules_process_group')
  isExampleOptions.value[1].inputProps.options = responseProcess.data.properties.meta
  processGroup.value = responseProcess.data.properties.meta
}
// pageSize改变时触发
const myChangePageSize = (data: FilterDataType) => {
  changePageSize(data)
  getData()
}
// current-page改变时触发
const myChangeCurrent = (value) => {
  changeCurrent(value)
  getData()
}
// 重置查询条件
const resetGetData = (data: FilterDataType) => {
  search.value = data
  search.value.level.checkAll = false
  changeCurrent(1)
  changePageSize(10)
  getData()
}
// onBeforeMount(getEventResource)
onBeforeMount(async () => {
  await getEventResource()
  getTreeData()
  getData()
})
</script>
<style lang="less" scoped>
.container {
  display: flex;
  align-items: stretch;
  justify-content: center;
  background: #f5f7f9;
  min-height: 100%;
  overflow: hidden;

  .companyTree {
    padding: 24px;
    margin: 12px 0 24px 0;
    background: #fff;
    border-radius: 8px;

    .title {
      font-size: 16px;
      font-family: HarmonyOS_Sans_SC_Medium;
      border-left: #2f7df1 2px solid;
      text-indent: 1em;
      color: #353a42;
      line-height: 30px;
      height: 30px;
      margin: 10px 0;
      display: flex;
      justify-content: space-between;
    }

    .search {
      margin-bottom: 20px;
    }

    /deep/ .el-tree-node__content {
      height: 32px;

    }

    /deep/ .el-tree-node:focus>.el-tree-node__content {
      background-color: #5daaf0; //背景色
    }

    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
      width: 100%;
      // background-color: yellow;

      .custom-tree-node-left {
        max-width: 300px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;

        .custom-tree-node-left-label {
          width: 100%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .oper {
        display: flex;
        justify-content: center;
        align-items: center;
        user-select: none;
        padding-right: 0px;
        width: 100px;

        img {
          width: 20px;
          height: 20px;
          object-fit: contain;

          &:hover {
            transform: scale(1.1);
          }
        }

        img+img {
          margin-left: 8px;
        }

        .border {
          border-radius: 4px;
          border: 1px solid #2f7df1;
          padding: 2px;
          box-sizing: border-box;
          margin-left: 8px;
        }
      }
    }
  }
}

.el-input__icon {
  margin: 0 5px;
}

.el-input__icon:hover {
  cursor: pointer;
}

.elRadio {
  display: flex;
  flex-direction: column;
  align-items: start;
  padding-left: 20px;
  /deep/ .el-radio__label {
    width: 100% !important;
    text-overflow: ellipsis;
    white-space: normal;
    line-height: 18px;
    word-break:break-all;
  }
}

.daoru {
  display: flex;
  justify-content: center;
}</style>
